<?php
namespace app\common\service;

use app\admin\service\CompanyService;
use app\admin\service\PointService;
use app\common\model\SystemCompany;
use app\common\model\SystemContract;
use app\common\model\SystemGoods;
use app\common\model\SystemMemberCount;
use think\Db;

class GoodsService{
    public static function buy($mid,$gid)
    {
        $company = SystemCompany::where('mid','=',$mid)->find();
        $master_company = CompanyService::getMaster($company['id']);
        $contract = SystemContract::where('mid','=',$mid)->find();
        $goods = SystemGoods::where('status','=',1)->find($gid);
        $goods_detail = Db::name('system_goods as sg')
            ->join('system_goods_detail sgd','sg.id=sgd.goods_id')
            ->join('system_service ss','ss.id=sgd.service_id')
            ->where('sg.id','=',$gid)
            ->field([
                'sgd.service_id' => 'service_id',
                'sgd.time' => 'time',
                'ss.title' => 'name',
            ])
            ->select();
//        Db::startTrans();
//        try {
        if ($master_company['point'] >= $goods['cost']){
            CompanyService::pointChange($master_company['id'],$goods['cost'],2);
            foreach ($goods_detail as $k=>$v){
                $service = Db::name('system_service')->find($v['service_id']);
                $member_count = SystemMemberCount::where([
                    'member_id'=>$mid,
                    'company_id'=>$company['id'],
                    'contract_id'=>$contract['id'],
                    'service_id'=>$v['service_id'],
                ])->find();
                if ($member_count){
                    SystemMemberCount::where([
                        'member_id'=>$mid,
                        'company_id'=>$company['id'],
                        'contract_id'=>$contract['id'],
                        'service_id'=>$v['service_id'],
                    ])->setInc('surplus',$v['time']);
                }else{
                    SystemMemberCount::insert([
                        'member_id'=>$mid,
                        'company_id'=>$company['id'],
                        'contract_id'=>$contract['id'],
                        'service_id'=>$v['service_id'],
                        'surplus'=>$v['time'],
                    ]);
                }
                sysoplog('会员管理', '购买商品' . $master_company['name'] . '成功');
                $log_res = PointService::frequencyDetAdd($mid, $mid, $contract['id'], $v['service_id'], 1, $v['time'], $goods['code'].'-'.$goods['name'], $master_company['unique']);
            }
            Db::commit();
            return true;
        }else{
            return false;
        }
//        } catch (\Exception $exception) {
//            Db::rollback();
//            return false;
//        }
    }
}
